package br.com.loja.util.converter;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @brief Classe StringParser
 * @author David Luiz
 * @date 03/12/2014
 */
public class ViewParser {

    public static String getStringOf(Object value) {
        return value.toString();
    }

    public static Calendar getCalendarOf(String value) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getDateOf(value));

        return calendar;
    }

    public static Date getDateOf(String value) throws IllegalArgumentException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date(1900, 1, 1);
        try {
            date = dateFormat.parse(value);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Erro ao tentar ler a data", e);
        }
        return date;
    }

    public static Number getNumberOf(String string, Class<? extends Number> clazz) {

        Object value = null;

        try {
            Constructor c = clazz.getConstructor(String.class);
            value = c.newInstance(string);

        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("Erro ao tentar converter valor", e.getTargetException());

        } catch (InstantiationException | IllegalAccessException | SecurityException | NoSuchMethodException ex) {
            throw new IllegalArgumentException("Erro ao tentar converter valor", ex);
        }

        return (Number) value;

    }

}
